<script setup>
import { ref, reactive, onMounted, provide } from 'vue'
import { getAllStore, searchStore } from '../http/api.js'
import { useRoute, useRouter } from 'vue-router'
import { useStore } from 'vuex'
import Cart from '../components/cart.vue'
import AMapLoader from '@amap/amap-jsapi-loader'
import { gcj02towgs84 } from '@/utils/gcj02towgs84'

const typeVal = ref(-1)
const orderVal = ref(0)
const route = useRoute()
const router = useRouter()
const store = useStore()
const cartNum = ref(0)
provide('cartNum', cartNum)
const orderOption = [
  {
    text: '综合排序',
    value: 0
  },
  {
    text: '距离优先',
    value: 1
  },
  {
    text: '评分优先',
    value: 2
  }
]
const typeOption = [
  {
    text: '类型选择',
    value: -1
  },
  {
    text: '火锅',
    value: 0
  },
  {
    text: '冒菜',
    value: 1
  },
  {
    text: '小炒',
    value: 2
  }
]
const storeRank = ref(3.5)
const searVal = ref('')
const data = reactive({
  storeList: {},
  lat: 0,
  lon: 0,
  address: ''
})
const loading = ref(false)
const onRefresh = () => {
  setTimeout(() => {
  }, 1000)
}
const onSearch = async () => {
  console.log('搜索内容', searVal.value)
  const rst = await searchStore(searVal.value)
  console.log('搜索结果', rst)
  data.storeList = rst.data
  console.log('渲染', data.storeList)
}

const getLocation = () => {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function (result) {
      console.log('位置信息', result)
      data.lat = result.coords.latitude
      data.lon = result.coords.longitude
      getLocation1()
    }, function (error) {
      console.log('获取失败', error)
    })
  } else {
    console.log('fail position')
  }
}
const getLocation1 = () => {
  AMapLoader.load({
    key: 'f76d4f59f0a16f228c4788f7e8bbd066', // 申请好的Web端开发者Key，首次调用 load 时必填
    version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: ['AMap.Geocoder'] // 需要使用的的插件列表，如比例尺'AMap.Scale'等
  }).then((AMap) => {
    const geocoder = new AMap.Geocoder({
      city: '010', // 城市设为北京，默认：“全国”
      radius: 1000 // 范围，默认：500
    })
    const lnglat = [data.lon, data.lat]
    geocoder.getAddress(lnglat, function (status, result) {
      console.log(result, status)
      if (status === 'complete' && result.regeocode) {
        console.log(result)
        const province = result.regeocode.addressComponent.province
        const city = result.regeocode.addressComponent.city
        const district = result.regeocode.addressComponent.district
        const street = result.regeocode.addressComponent.street
        data.address = province + city + district + street
        console.log(data.address)
      } else {
        console.log('根据经纬度查询地址失败')
      }
    })
  }).catch(e => {
    console.log(e)
  })
}
const allStore = async () => {
  const rst = await getAllStore()
  console.log('店铺列表', rst)
  data.storeList = rst
}
const startSearch = () => {
  if (searVal.value !== '') {
    console.log('开始search')
    onSearch()
  } else {
    allStore()
  }
}
const onClear = () => {
  allStore()
}
const goodsList = (stId) => {
  console.log('home-stId', stId)
  router.push({
    path: '/goods_list',
    query: {
      stId: stId
    }
  })
}
onMounted(() => {
  window._AMapSecurityConfig = {
    securityJsCode: '9aa80dda621dac4ded120bc8a623421d'
  }
  getLocation()
  allStore()
  // 重载购物车属性
  cartNum.value = store.getters.cart_item_num
})
</script>

<template>
  <div class="home">
    <Cart></Cart>
    <div class="head">
      <span class="logoText">吃了么</span>
      <div class="loca" @click="getLocation">
        <van-icon name="location-o"/>
        <span>{{data.address}}</span>
      </div>
    </div>
    <van-sticky>
      <div class="searBox">
        <van-search v-model="searVal" placeholder="请输入搜索关键词" @search="onSearch" @blur="startSearch" @clear="onClear"/>
      </div>
      <div class="chooseBox">
        <van-dropdown-menu>
          <van-dropdown-item v-model="orderVal" :options="orderOption"/>
          <van-dropdown-item v-model="typeVal" :options="typeOption"/>
        </van-dropdown-menu>
      </div>
    </van-sticky>
    <div class="store_list">
      <!-- 商家列表 -->
      <van-pull-refresh v-model="loading" @refresh="onRefresh">
          <div class="store_item" v-for="item in data.storeList" :key="item.stId" @click="goodsList(item.stId)">
          <van-image width="100" height="100" :src="item.stCimg"/>
          <div class="store_info">
            <span class="store_name">{{ item.stName }}</span>
            <div class="tags">
              <van-tag plain type="primary">月售3000+</van-tag>
              <van-tag plain type="primary">998m</van-tag>
              <van-tag plain type="primary">起送0</van-tag>
            </div>
            <div class="titles">
              <van-tag type="primary">四川省第一</van-tag>
            </div>
            <div class="rank">
              <van-rate
                v-model="item.stScore"
                :size="20"
                color="#ffd21e"
                void-icon="star"
                void-color="#eee"
                :allow-half="true"
              />
            </div>
          </div>
        </div>
      </van-pull-refresh>
    </div>
  </div>
</template>

<style scoped>
.store_list {
  margin: 6px 0 80px 0;
}

.tags span {
  margin-right: 6px;
}

.store_name {
  font-weight: 600;
}

.store_info {
  display: flex;
  flex-direction: column;
  flex-grow: 1;
  align-items: flex-start;
  margin-left: 6px;
  justify-content: space-around;
}

.store_item {
  display: flex;
  padding: 6px;

}

.loca {
  font-size: .88rem;
}

.logoText {
  font-size: 1.2rem;
}

.head {
  min-height: 60px;
  border: 1px solid;
  display: flex;
  align-items: center;
  justify-content: space-around;
  background-color: #00A4FF;
  color: white;
  border-radius: 6px;
}

.home {
  padding: 5px;
}
</style>
